package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1 获取请求标记
            //获取Servlet一级目录后面的路径 ，也就是/list、/save、/edit、/delete 等
            String s = req.getPathInfo().substring(1);
            //2 获取对应方法Method对象,this表示子类对象
            Method method = this.getClass().getDeclaredMethod(s, HttpServletRequest.class, HttpServletResponse.class);
            //3 开启访问权限，暴力访问
            method.setAccessible(true);

            //4 反射执行方法
            Object result = method.invoke(this, req, resp);
            //将result对象响应给客户端
            objectMapper.writeValue(resp.getOutputStream(),result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
